﻿namespace LowCoding.Common
{
    public static class AjaxResultExtensions
    {
        public static bool IsSuccess(this AjaxResult result)
        {
            if (result.state == ResultType.success)
                return true;
            return false;
        }

        public static bool IsSuccess<T>(this AjaxResult<T> result)
        {
            if (result.state == ResultType.success)
                return true;
            return false;
        }

        public static bool IsEmptyBlock(this AjaxResult result)
        {
            if (result.data.ToJson() == "[]")
                return true;
            return false;
        }

        public static T To<T>(this AjaxResult result) where T : class
        {
            if (!result.IsSuccess()) throw new Exception(result.message);
            if (result.data == null) throw new Exception("查询数据未空");
            var model = result.data as T;
            if (model == null) throw new Exception("数据为空");
            return model;
        }

        public static List<T> ToList<T>(this AjaxResult result) where T : class
        {
            if (!result.IsSuccess()) throw new Exception(result.message);
            if (result.data == null) throw new Exception("查询数据未空");
            return result.data as List<T>;
        }

        public static AjaxResult Success()
        {
            return new AjaxResult { state = ResultType.success, message = "OK" };
        }

        public static AjaxResult Success(string message)
        {
            return new AjaxResult { state = ResultType.success, message = message };
        }

        public static AjaxResult Success(string message, object data)
        {
            return new AjaxResult { state = ResultType.success, message = message, data = data };
        }

        public static AjaxResult<T> Success<T>(T t)
        {
            return new AjaxResult<T> { state = ResultType.success, data = t };
        }

        public static AjaxResult Error(string message)
        {
            return new AjaxResult { state = ResultType.error, message = message };
        }

        public static AjaxResult Error(int code, string message)
        {
            return new AjaxResult { state = (ResultType)code, message = message };
        }
    }
}